package utils;

import java.io.File;
import java.io.IOException;
import java.io.PrintStream;

/**
 * This is system console redirection class.
 * 
 * @author Uros Krkic
 */
public final class ConsoleRedirect {

	public static final int STD_OUT	= 0;
	public static final int STD_ERR	= 1;
	
	
	private ConsoleRedirect() { }
	
	
	/**
	 * This method redirects console output to file specified.<br>
	 * By default, the specified file is: ./log/console.txt
	 * @author Uros Krkic
	 */
	public static void redirectToFile() {
		redirectToFile("./log/console.txt", STD_OUT);
		redirectToFile("./log/error.txt", STD_ERR);
	}
	
	
	/**
	 * This method redirects console output to file specified.<br>
	 * @param fileName - the file that stores console output
	 * @param type - type of redirection - possible values: STD_OUT, STD_ERR
	 * @author Uros Krkic
	 */
	public static void redirectToFile(String fileName, int type) {
		try {
			File file = new File(fileName);
			file.createNewFile();
			
			PrintStream stream = new PrintStream(file);
			
			if (type == STD_OUT) {
				System.setOut(stream);
				return;
			}
			
			if (type == STD_ERR) {
				System.setErr(stream);
				return;
			}
		}
		catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
	
	
	/**
	 * This method resets console redirection to system default - stdout.
	 * @author Uros Krkic
	 */
	public static void redirectToDefault() {
		System.setOut(System.out);
		System.setErr(System.err);
	}
	
}
